package com.catena.mock.core;

import com.catena.mock.MockRuntimeException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
import java.util.concurrent.ConcurrentSkipListMap;

/**
 * Created by hx-pc on 16-9-28.
 */
public class ScanProjectContext {

    private static final Logger LOGGER = LoggerFactory.getLogger(ScanProjectContext.class);
    private Map<String, String> environmentMap = new ConcurrentSkipListMap<>();
    private Map<String, ScanContext> projectMap = new ConcurrentSkipListMap<>();
    public static final String PROJECT_VERSION = "project.version";
    public static final String API_KEY = "api.key";
    public static final String DATA_GET_KEY = "data.get.key";
    public static final String DATA_POST_KEY = "data.post.key";
    public static final String DATA_PUT_KEY = "data.put.key";
    public static final String DATA_DELETE_KEY = "data.delete.key";
    public static final String DATA_CONTENT_GET_KEY = "data.content.get.key";
    public static final String DATA_CONTENT_POST_KEY = "data.content.post.key";
    public static final String DATA_CONTENT_PUT_KEY = "data.content.put.key";
    public static final String DATA_CONTENT_DELETE_KEY = "data.content.delete.key";
    private static final Object object = new Object();

    public ScanProjectContext() throws IOException {
        synchronized (object) {
            loadEnvironment();
            init();
        }
    }

    private void init() throws IOException {
        String[] projects = getProjects();
        for (String project : projects) {
            projectMap.put(project, new ScanContext(project, environmentMap.get(API_KEY)));
        }
    }

    private void loadEnvironment() throws IOException {
        File rootDir = new File("projectEnvironment/");
        File[] file = rootDir.listFiles();
        if (!file[0].exists() && file[0].getName().contains("environment")) {
            LOGGER.error("projectEnvironment/environment.properties 文件不存在");
            throw new MockRuntimeException(404, "环境配置文件environment不存在请创建");
        }
        BufferedReader reader = getBufferReader(file[0]);
        String readLine = reader.readLine();
        while (readLine != null) {
            analyzeEnvLineStr(new StringBuilder(readLine));
            readLine = reader.readLine();
        }
        reader.close();
    }

    private void analyzeEnvLineStr(StringBuilder lineStr) {
        String str = lineStr.toString().replace("\n", "");
        if (str.length() > 0 && !str.startsWith("#")) {
            int indexEqual = str.lastIndexOf('=') + 1;
            String beforePt = str.substring(0, indexEqual - 1);
            String afterPt = str.substring(indexEqual);
            environmentMap.put(beforePt, afterPt);
        }
    }

    private BufferedReader getBufferReader(File file) throws UnsupportedEncodingException, FileNotFoundException {
        InputStreamReader isr = new InputStreamReader(new FileInputStream(file), "utf-8");
        return new BufferedReader(isr);
    }

    private BufferedWriter getBufferWriter(File file) throws UnsupportedEncodingException, FileNotFoundException {

        OutputStreamWriter isr = new OutputStreamWriter(new FileOutputStream(file), "utf-8");
        return new BufferedWriter(isr);
    }

    public Map<String, String> getEnvironmentMap() {
        return environmentMap;
    }

    public ScanContext getScanContext(String project) {
        return projectMap.get(project);
    }

    public String[] getProjects() {
        return environmentMap.get(PROJECT_VERSION).split(",");
    }

    public void addProject(String project) throws IOException {
        File file = new File("projectEnvironment/").listFiles()[0];
        File newFile = new File("projectEnvironment/environment" + new SimpleDateFormat("yyyy-MM-dd hh:mm:ss SSS").format(new Date()) + ".properties");
        BufferedReader reader = getBufferReader(file);
        BufferedWriter writer = getBufferWriter(newFile);
        String readLine = reader.readLine();
        writer.write(readLine);
        writer.newLine();
        while (readLine != null) {
            analyzeEnvLineStr(new StringBuilder(readLine));
            readLine = reader.readLine();
            if (readLine != null) {
                if (readLine.contains(PROJECT_VERSION)) {
                    readLine = readLine + "," + project;
                }
                writer.write(readLine);
                writer.newLine();
            }
        }
        reader.close();
        file.delete();
        writer.flush();
        writer.close();
    }

    public void deleteProject(String project) throws IOException {
        File file = new File("projectEnvironment/").listFiles()[0];
        File newFile = new File("projectEnvironment/environment" + new SimpleDateFormat("yyyy-MM-dd hh:mm:ss SSS").format(new Date()) + ".properties");
        BufferedReader reader = getBufferReader(file);
        BufferedWriter writer = getBufferWriter(newFile);
        String readLine = reader.readLine();
        writer.write(readLine);
        writer.newLine();
        while (readLine != null) {
            analyzeEnvLineStr(new StringBuilder(readLine));
            readLine = reader.readLine();
            if (readLine != null) {
                if (readLine.contains(PROJECT_VERSION)) {
                    readLine = readLine.replace(project, "").replace(",,","");
                }
                writer.write(readLine);
                writer.newLine();
            }
        }
        reader.close();
        file.delete();
        writer.flush();
        writer.close();
    }

    public void reset() throws IOException {
        synchronized (object) {
            loadEnvironment();
            init();
        }
    }
}
